const Base = require('./base.js');
const captcha = require('svg-captcha')
const CODE_CACHE_TIME = 15 * 1000 * 60;
function guid(){
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
    var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  }).toLowerCase();
}

module.exports = class extends Base {
  async indexAction() {
    return this.display();
  }

  async captchaAction(){
    // 设置code
    // 获取key值
    let key = this.cookie('session_id');
    key = 'verification-code-'+key;
    const { height = 34, width = 120, fontSize = 50, background ='rgba(223, 246, 234, 1)', noise = 2 } = {}
    const { data, text } = captcha.create({ height, width, fontSize, background, noise });
    let code = text;
    let ret = data;
    console.log(text);
    await this.cache(key,code,{
      timeout:CODE_CACHE_TIME
    })
    return this.success(data)
  }

  async userstudyAction() {
    const {name, phone, wechat,code:userCode} = this.post();

    //校验证码
    let key = this.cookie('session_id');
    key = 'verification-code-'+key;
    const code = await this.cache(key)
    if(code.toLowerCase() !== userCode.toLowerCase()){
      return this.fail('对不起验证码校验失败')
    }

    const model = this.model('user_study');
    try {
      const res = await model.add({name, phone, wechat});
      if (!think.isEmpty(res)) {
        return this.success(200, '插入成功');
      } else {
        this.fail(200, '插入失败');
      }
      // return this.success(200, '插入成功')
    } catch (e) {
      return this.fail(200, e.message);
    }
  }
};
